<template>
    <!-- 发送短信验证码，案例使用element-plus作为框架，其他UI框架请适当修改 -->
    <el-form :model="formData" ref="formDataRef">
        <p style="margin-top: 2em;font-weight: bold;">安全验证</p>
        <p class="desc">为确保本次操作的安全性，请输入发送至 {{ formData.mobile }} 手机的验证码</p>
        <el-form-item label="" prop="code" :rules="[{ required: true, message: '请输入手机验证码', }]">
            <el-input v-model="formData.code" maxlength="15" placeholder="手机验证码" style="width: 25em;">
                <template #suffix>
                    <el-link type="primary" @click.stop="sendMessage" v-if="formData.timeLeft === 0">发送验证码</el-link>
                    <el-link type="primary" v-else disabled>{{ formData.timeLeft }}秒</el-link>
                </template>
            </el-input>
        </el-form-item>
        <el-form-item label="" style="margin-top: 2em;">
            <el-button type="primary" size="large" style="width: 8em;" @click.stop="submitCredit">提交</el-button>
        </el-form-item>
    </el-form>

</template>

<script setup>
import { reactive, ref, } from 'vue';

const config = {
    maxSeconds: 60, // 最大秒数
}
const formDataRef = ref();
const formData = reactive({
    code: '',
    mobile: '',
    timer: '',
    timeLeft: 0,
});


const sendMessage = async ()=>{
    if(formData.timeLeft){
        return;
    }

    await Promise.resolve('请求发送短信请求');
    formData.timeLeft = config.maxSeconds;
    formData.timer = setInterval(()=>{
        formData.timeLeft--;
        if(formData.timeLeft<=0){
            clearInterval(formData.timer);
            formData.timeLeft = 0;
        }
    },1000)
}

const submitCredit = ()=> {
    formDataRef.value?.validate((valid)=>{
        if(valid){
            // ... 提交数据
        }
    })
}
</script>

